package com.chen.util;

import cn.hutool.core.io.FileUtil;
import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.jar.JarFile;

/**
 * @Author:chenao
 * @DATE:2022/3/12 19:22
 */
public class PathUtils {
    private static volatile String CURRENT_JAR_PARENT_PATH = null;

    /**
     * 获取文件存储路径，在jar包同级目录
     * @return
     */
    public static String getUploadPath(){
        String jarPath = getCurrentJarParentPath();
        String uploadPath =jarPath+ File.separator+"upload"+File.separator;
        if(!FileUtil.exist(uploadPath)){
            FileUtil.mkdir(uploadPath);
        }
        System.out.println(uploadPath);
        return uploadPath;
    }

    /**
     * 获取当前Jar包路径
     * @return
     */
    public static String getCurrentJarParentPath() {
        if (CURRENT_JAR_PARENT_PATH == null) {
            synchronized (PathUtils.class) {
                if (CURRENT_JAR_PARENT_PATH == null) {
                    File jarFile = applicationHome(PathUtils.class);
                    if (jarFile != null) {
                        CURRENT_JAR_PARENT_PATH = jarFile.getParent();
                        return CURRENT_JAR_PARENT_PATH;
                    }
                    throw new RuntimeException("获取当前jar文件路径异常，中止服务");
                }
            }
        }
        return CURRENT_JAR_PARENT_PATH;
    }

    private static File applicationHome(Class<?> sourceClass) {
        try {
            ProtectionDomain domain = sourceClass != null ? sourceClass.getProtectionDomain() : null;
            CodeSource codeSource = domain != null ? domain.getCodeSource() : null;
            URL location = codeSource != null ? codeSource.getLocation() : null;
            File source = location != null ? findSource(location) : null;
            if (source != null && source.exists()) {
                return source.getAbsoluteFile();
            }
        } catch (Exception exception) {
            System.out.println("获取路径异常");
        }
        return null;
    }

    private static File findSource(URL location) throws IOException, URISyntaxException {
        URLConnection connection = location.openConnection();
        return connection instanceof JarURLConnection ? getRootJarFile(((JarURLConnection) connection).getJarFile()) : new File(location.toURI());
    }

    private static File getRootJarFile(JarFile jarFile) {
        String name = jarFile.getName();
        int separator = name.indexOf("!/");
        if (separator > 0) {
            name = name.substring(0, separator);
        }
        return new File(name);
    }
}
